// miniprogram/pages/detail/detail.js
const db = wx.cloud.database()
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id: "",
    detail: { content: "", name: "", createTime: "" }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { id } = options
    const that = this
    db.collection('logs').where({
      _id: id
    }).get().then(res => {
      const detail = res.data
      that.setData({ detail: detail[0], id })
    

    })
    db.collection('likes').where({
      logId: id, // 填入当前用户 openid
      _openid:app.globalData.openid,
      type:true
    }).count().then(res => {
      console.log(res)
      if (res.total !== 0) {
        that.setData({ likeStatus: true })
      }
    })
  },
  update:function(){
    const {id}=this.data
    wx.showModal({
      content: '发布到广场？',
      success (res) {
        if (res.confirm) {
          db.collection('logs').doc(id).update({
            data: {
              open: true,
              like:0,
              nolike:0
            },
          }).then(
            wx.switchTab({
              url: '../mine/mine',
            })
          )
        } 
      }
    })
  },
  nolike:function(){
    const {id}=this.data
    const that=this
    wx.showModal({
      content: '不喜欢了？',
      success (res) {
        if (res.confirm) {
          db.collection('logs').where({
            _id: id
          }).get().then(res => {
            console.log(res.data)
          db.collection('logs').doc(id).update({
            data: {
              nolike: res.data[0].nolike + 1,
              like:  res.data[0].like -1
            },
          })
        })
        that.changeLike(id, false)
        } 
      }
    })
  },
  changeLike:function(id, type){
    db.collection('likes').where({
      logId: id,
      _openid: app.globalData.openid// 填入当前用户 openid
    }).count().then(res => {
        db.collection('likes').where({
          logId: id
        }).get().then(res => {
          db.collection('likes').doc(res.data[0]._id).set({
            data: {
              logId: id,
              type
            }
          })
            .then(() => {
              wx.navigateBack()
            })
            .catch(console.error)
        })
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
 * 生命周期函数--监听页面显示
 */
  onShow: function () {

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})